// src/utils/request.js
import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: 'http://localhost:3005/', // 设置全局基础 URL
  timeout: 5000, // 设置请求超时时间
})

request.interceptors.request.use(function (config) {
  const accessToken = localStorage.getItem('access_token')

  if (accessToken) {
    config.headers.authorization = 'Bearer ' + accessToken
  }

  return config
})

request.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    let { data, config } = error.response

    if (data.code === 401 && !config.url.includes('/user/admin/refresh')) {
      const res = await refreshToken()

      if (res.status === 200 || res.status === 201) {
        return request(config)
      } else {
        ElMessage.error(res.data.data)

        setTimeout(() => {
          window.location.href = '/login'
        }, 1000)
      }
    } else {
      return error.response
    }
  },
)

async function refreshToken() {
  const res = await request.get('/user/admin/refresh', {
    params: {
      refresh_token: localStorage.getItem('refresh_token'),
    },
  })
  localStorage.setItem('access_token', res.data.access_token)
  localStorage.setItem('refresh_token', res.data.refresh_token)
  return res
}

export default request
